'use client';

import { useState, ReactNode, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { 
  Menu, 
  X, 
  Search,
  Bell,
  Sun,
  Moon,
  LogOut,
  Settings,
  User,
  ChevronDown,
  ChevronRight,
  Palette,
  Monitor,
  ChevronsLeft
} from 'lucide-react';
import { useTheme } from '@/providers/theme-provider';
import { menusConfig, type ModernNavType } from '@/config/menus';
import { themes } from '@/config/themes';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  DropdownMenuCheckboxItem,
} from '@/components/ui/dropdown-menu';
import { cn, truncateUserId } from '@/lib/utils';

interface EnhancedDashboardLayoutProps {
  children: ReactNode;
  userId: string;
}

interface MenuItemComponentProps {
  item: ModernNavType;
  userId: string;
  pathname: string;
  collapsed: boolean;
}

function MenuItemComponent({ item, userId, pathname, collapsed }: MenuItemComponentProps) {
  const [isOpen, setIsOpen] = useState(false);
  const hasChildren = item.child && item.child.length > 0;
  
  if (!hasChildren && item.href) {
    const Icon = item.icon;
    const href = `/${userId}${item.href}`;
    const isActive = pathname === href;
    
    return (
      <Link
        href={href}
        className={cn(
          "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground",
          isActive && "bg-primary text-primary-foreground hover:bg-primary/90",
          collapsed && "justify-center px-2"
        )}
        title={collapsed ? item.title : undefined}
      >
        <Icon className="h-4 w-4 flex-shrink-0" />
        {!collapsed && <span>{item.title}</span>}
      </Link>
    );
  }

  if (hasChildren) {
    const Icon = item.icon;
    
    return (
      <div>
        <button
          onClick={() => setIsOpen(!isOpen)}
          className={cn(
            "flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all hover:bg-accent hover:text-accent-foreground",
            collapsed && "justify-center px-2"
          )}
          title={collapsed ? item.title : undefined}
        >
          <Icon className="h-4 w-4 flex-shrink-0" />
          {!collapsed && (
            <>
              <span className="flex-1 text-left">{item.title}</span>
              <ChevronRight className={cn("h-4 w-4 transition-transform", isOpen && "rotate-90")} />
            </>
          )}
        </button>
        
        {!collapsed && isOpen && item.child && (
          <div className="ml-4 mt-1 space-y-1">
            {item.child.map((child) => {
              const ChildIcon = child.icon;
              const href = `/${userId}${child.href}`;
              const isActive = pathname === href;
              
              return (
                <Link
                  key={child.href}
                  href={href}
                  className={cn(
                    "flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-all hover:bg-accent hover:text-accent-foreground",
                    isActive && "bg-primary text-primary-foreground hover:bg-primary/90"
                  )}
                >
                  <ChildIcon className="h-4 w-4" />
                  <span>{child.title}</span>
                </Link>
              );
            })}
          </div>
        )}
      </div>
    );
  }

  return null;
}

export default function EnhancedDashboardLayout({ children, userId }: EnhancedDashboardLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mounted, setMounted] = useState(false);
  const { theme, mode, setTheme, setMode, toggleMode } = useTheme();
  const pathname = usePathname();

  useEffect(() => {
    setMounted(true);
  }, []);

  const toggleSidebar = () => setSidebarOpen(!sidebarOpen);
  const toggleCollapsed = () => setSidebarCollapsed(!sidebarCollapsed);

  // Prevent hydration mismatch - show loading state until mounted
  if (!mounted) {
    return (
      <div className="min-h-screen bg-background">
        <div className="flex items-center justify-center h-screen">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Sidebar */}
      <aside className={cn(
        // Mobile: fixed overlay sidebar
        "fixed inset-y-0 left-0 z-50 bg-card shadow-lg border-r transition-all duration-300 ease-in-out",
        sidebarCollapsed ? "w-16" : "w-64",
        sidebarOpen ? "translate-x-0" : "-translate-x-full",
        // Desktop: always visible, positioned
        "lg:translate-x-0"
      )}>
        
        {/* Sidebar Header */}
        <div className="flex items-center justify-between h-16 px-4 border-b">
          {!sidebarCollapsed && (
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
                <div className="w-4 h-4 bg-primary-foreground rounded-sm"></div>
              </div>
              <span className="text-lg font-bold">Dashboard</span>
            </div>
          )}
          
          <div className="flex items-center space-x-2">
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleCollapsed}
              className="hidden lg:flex"
            >
              <ChevronsLeft className={cn("h-4 w-4 transition-transform", sidebarCollapsed && "rotate-180")} />
            </Button>
            
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleSidebar}
              className="lg:hidden"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Navigation Menu */}
        <nav className="flex-1 space-y-2 p-4 overflow-y-auto">
          {menusConfig.sidebarNav.modern.map((item, index) => (
            <MenuItemComponent
              key={index}
              item={item}
              userId={userId}
              pathname={pathname}
              collapsed={sidebarCollapsed}
            />
          ))}
        </nav>

        {/* User Profile Card */}
        {!sidebarCollapsed && (
          <div className="p-4 border-t">
            <div className="bg-muted rounded-lg p-3">
              <div className="flex items-center space-x-3">
                <img
                  src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${userId}`}
                  alt="User Avatar"
                  className="w-8 h-8 rounded-full"
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">
                    {truncateUserId(userId)}
                  </p>
                  <p className="text-xs text-muted-foreground">Premium</p>
                </div>
              </div>
            </div>
          </div>
        )}
      </aside>

      {/* Main Content Area */}
      <div className={cn(
        "flex flex-col min-h-screen transition-all duration-300",
        // Desktop: add left margin for sidebar
        sidebarCollapsed ? "lg:ml-16" : "lg:ml-64"
      )}>
        {/* Top Navigation */}
        <header className="bg-card shadow-sm border-b h-16 px-6 flex-shrink-0">
          <div className="flex items-center justify-between h-full">
            {/* Left side */}
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="icon"
                onClick={toggleSidebar}
                className="lg:hidden"
              >
                <Menu className="h-5 w-5" />
              </Button>
              
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Search..."
                  className="pl-10 pr-4 py-2 border border-input rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:border-ring w-64"
                />
              </div>
            </div>

            {/* Right side */}
            <div className="flex items-center space-x-4">
              {/* Theme Selector */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon">
                    <Palette className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-48">
                  <DropdownMenuLabel>Theme</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  {themes.map((t) => (
                    <DropdownMenuCheckboxItem
                      key={t.name}
                      checked={theme === t.name}
                      onCheckedChange={() => setTheme(t.name)}
                    >
                      {t.label}
                    </DropdownMenuCheckboxItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>

              {/* Mode Toggle */}
              <Button variant="ghost" size="icon" onClick={toggleMode}>
                {mode === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
              </Button>

              {/* Notifications */}
              <Button variant="ghost" size="icon" className="relative">
                <Bell className="h-4 w-4" />
                <span className="absolute -top-1 -right-1 h-4 w-4 bg-destructive rounded-full text-xs text-destructive-foreground flex items-center justify-center">
                  3
                </span>
              </Button>

              {/* User Menu */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="flex items-center space-x-2">
                    <img
                      src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${userId}`}
                      alt="User Avatar"
                      className="h-8 w-8 rounded-full"
                    />
                    <div className="hidden sm:block text-left">
                      <p className="text-sm font-medium max-w-[120px] truncate">
                        {truncateUserId(userId)}
                      </p>
                      <p className="text-xs text-muted-foreground">Premium</p>
                    </div>
                    <ChevronDown className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56">
                  <DropdownMenuLabel>My Account</DropdownMenuLabel>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem asChild>
                    <Link href={`/${userId}/profile`}>
                      <User className="mr-2 h-4 w-4" />
                      Profile
                    </Link>
                  </DropdownMenuItem>
                  <DropdownMenuItem asChild>
                    <Link href={`/${userId}/settings`}>
                      <Settings className="mr-2 h-4 w-4" />
                      Settings
                    </Link>
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem>
                    <LogOut className="mr-2 h-4 w-4" />
                    Log out
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main className="flex-1 p-4 sm:p-6 overflow-auto">
          {children}
        </main>
      </div>

      {/* Mobile Sidebar Overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-40 bg-black bg-opacity-50 lg:hidden"
          onClick={toggleSidebar}
        />
      )}
    </div>
  );
} 